/* Drag and Drop do Carrinho */
$(document).ready(function() {
        
        if ( $('body').is(':not(.carrinho)') ) {
        
            $("#searchform select").jQSelect();
            $("#footerheading .search select").jQSelect();
            $("#ctl00_Conteudo_ctrlEndereco_lstEstado").jQSelect();
            $("#ctl00_Conteudo_ctrlEndereco_ddlTipoEndereco").jQSelect();
            $("#ctl00_Conteudo_DadosPagamento_lbxEnderecoCobranca").jQSelect();
            
            if($("#produto .productabout .priceWrapper select").length>0 && $('body').is('.produto') ){
                $("#produto .productabout .priceWrapper select").jQSelectToList();
            }
            if($("#product .productabout .priceWrapper select").length>0){
                $("#product .productabout .priceWrapper select").jQSelectToList();
            }
            $("#departaments .menu-departamento ul").jQMaxmenu();
            $("#departaments-small ul").jQMaxmenu();
            $("#produto ul.thumbs").jQRoll();
            
		}
		$('.prateleira .photo').draggable({
			zIndex: 1000,
			opacity: 0.8,
			helper: "clone",
			revert: false,
			cursor: 'move',
			scroll: false,
			start: function(event, ui){
				$('#cartbuy .cart-info,#carrinho #menu').slideDown();
			},
			stop: function(event, ui){
				var x = $('#cartbuy .cart-info').offset();
				var x2 = $('#carrinho #menu').offset();
				if((ui.offset.top - x.top <= 50) && (x.left - ui.offset.left <= 50) && $('#cartbuy .cart-info').is(":visible")){
					buy(this);
					$('#cartbuy .cart-info').delay(2000).slideUp();
				} else if ((ui.offset.top - x2.top <= 50) && (x2.left - ui.offset.left <= 50) && $('#carrinho #menu').is(":visible")){
					buy(this);
					$('#cartbuy .cart-info').delay(2000).slideUp();
				} 
				else {
					$('#cartbuy .cart-info').slideUp();
				}
			}
		});
		
		/* Evita mecher na página ao clicar num link com # */
		$('a').click(function(event){
			if($(this).attr('href') == '#') {
				event.preventDefault();
			}
		});
		
		// When the mouse hover the product box.
		$('.prateleira li').mouseenter(function() {
			$(this).find('.quick-view').show();
			if($(this).find('.check').is(':hidden')){
				$(this).find('.add').show();
			}
		});
		// When the mouse leave the product box.
		$('.prateleira li').mouseleave(function() {
			$(this).find('.quick-view').hide();
			$(this).find('.add').hide();
		});
		
		// Left Banners animation.
		$('#special-shops li img').animate({ 'opacity' : 0.5 });
		$('#special-shops li img').mouseenter(function() {
			$(this).animate({ 'opacity' : 1 });
		});
		$('#special-shops li img').mouseleave(function() {
			$(this).animate({ 'opacity' : 0.5 });
		});
        
        
        $('#shop ul img').animate({ 'opacity' : 0.5 });
		$('#shop ul img').mouseenter(function() {
			$(this).animate({ 'opacity' : 1 });
		});
		$('#shop ul img').mouseleave(function() {
			$(this).animate({ 'opacity' : 0.5 });
		});
		
		// Footer Social animation.
		$('#footercontent .support img').animate({ 'opacity' : 0.5 });
		$('#footercontent .support img').mouseenter(function() {
			$(this).animate({ 'opacity' : 1 });
		});
		$('#footercontent .support img').mouseleave(function() {
			$(this).animate({ 'opacity' : 0.5 });
		});
		
		// Navigation
		$('#navigation ul').append('<div class="bottomcorners"> </div>');
		$('#navigation ul').find('li:last').css({ 'border-bottom' : '0 none' , 'padding-bottom' : '0'  })
		$('#navigation h3').mouseover(function() {
			$('#navigation h3').removeClass('hovered');
			$(this).addClass('hovered');
			$('#navigation ul').hide();
			var  pos = $(this).get(0);
			var child = $(this).next();
			$(child).show();
			$(child).css({ 'left' : pos.offsetLeft });
		});
		$('#navigation').mouseleave(function(){
			$('#navigation ul').hide();
			$('#navigation h3').removeClass('hovered');
		});
		
		
		$('.steps ul li:last-child').css({ 'border-right' : '0 none' });
		
		// Carrinho
		$('#linkCarrinho').click(function() {
			$('#cartbuy .cart-info').slideToggle();
		});
		
		// Showing the objects.
		$('#cartbuy,#loginform').show().css({ 'position' : 'absolute' });
		
		// Tabs
		$('#tabs li a').click(function() {
			$('#tabs li a').removeClass('active');
			$(this).addClass('active');
			var ckindex = $(this).index('#tabs li a');
			$('#tabscontent .tab').hide();
			$('#tabscontent .tab:eq(' + ckindex + ')').show();
		});
		
		$('.prodcontent .spanopenpayment').click(function () {
		
			$('.prodcontent .otherpaymentfield').toggle();
		
		});
		
		// The add button
		$('.vitrine .wrapper .add img').click(function() {
			buy(this);
			$('#cartbuy .cart-info').slideDown();
		
		});
		$('.prateleira li .add').mouseup(function() {
			$(this).fadeOut('fast');
			$('#cartbuy .cart-info').slideDown();
			$('#cartbuy .cart-info').delay(1000).slideUp();
		});
		
		
		// Barra suspensa superior 
		$(window).scroll(function(){
			if($(window).scrollTop() < 180){
				$('#carrinho-barra').fadeOut('normal');
			} else {
				$('#carrinho-barra').fadeIn('slow');
			}
		});
		$('#carrinho-barra #seta a').click(function(){
			$('#carrinho-barra *').hide();
			$('#carrinho-barra').animate({"top": "-=32px"}, 500, 'linear' ,function(){
				$('#carrinho-barra #seta2 *').show();
				$('#carrinho-barra #seta2').slideDown(300);
			});
		});
		$('#carrinho-barra select')
		$('#carrinho-barra #seta2 a').click(function(){
			$('#carrinho-barra #seta2').fadeOut(100);
			$('#carrinho-barra').animate({"top": "+=32px"}, 500, 'linear' ,function(){
				$('#carrinho-barra :not(#seta2,script,legend,label,select)').fadeIn('slow');
				$('#carrinho-barra #carrinho #menu').hide();
			});
		});

		
		
		// Conteúdo da login bar.	
		if ( $('#logonmsg:contains("cadastrado?")').size() == 0 ) {
			$('#loginform').html( $('#logonmsg').html());
		}
		
		  
		/* Carrousel das Marcas */
		if($('#marcas-up').length>0){
            
            function mycarousel_initCallback(carousel)
            {
                // Disable autoscrolling if the user clicks the prev or next button.
                carousel.buttonNext.bind('click', function() {
                    carousel.startAuto(0);
                });
             
                carousel.buttonPrev.bind('click', function() {
                    carousel.startAuto(0);
                });
             
                // Pause autoscrolling if the user moves with the cursor over the clip.
                carousel.clip.hover(function() {
                    carousel.stopAuto();
                }, function() {
                    carousel.startAuto();
                });
            };
        
			$('#marcas-up').jCarouselLite({circular: true, auto: 1, visible: 5,  auto: 1200, animation : 'slow', initCallback: mycarousel_initCallback, mouseWheel: true, btnNext: "#seta-dir", btnPrev: "#seta-esq"});
            
            $('#marcas-carr li').css({'margin-right' : '50px'  });
        
        }
		  items_carrinho();
		  
		$('.departamento #centercol').prepend('<div class="heading clearfix"><h3>Reference Recomenda</h3></div>');  
		$('.resultado-busca #centercol').prepend('<div class="semiheading clearfix"><h3>Reference Recomenda</h3></div>');  
		$('.categoria #centercol').prepend('<div class="semiheading clearfix"><h3>Reference Recomenda</h3></div>');  
		  
	
    $('#tabscontent .specification dd:even').addClass('odd');
    
    if ( $("#tabscontent .description .productDescription:empty").size() > 0 ){
    
        $('#tabscontent .description').remove();
        $('#tabs li:contains("Descri")').remove();
        $('#tabs li:first a').click();
    
    }
    
    if ( $("#tabscontent .specification #caracteristicas:empty").size() > 0 ){
    
        $('#tabscontent .specification').remove();
        $('#tabs li:contains("Dados")').remove();
        $('#tabs li:first a').click();
    
    }
    

    
	$('td.texto-cepline').append('<div id="freteinformation"> \
    Atenção: Compras para os estados do Acre, Alagoas, Amapá, Bahia, Ceará, Espírito Santo, Goiás, Maranhão, Mato Grosso, Pará, Paraíba, Pernambuco, Piauí, Rio Grande do Norte, Roraima, Rondônia e Sergipe terão acrescidos ao frete 7% do valor total das mercadorias, referente ao imposto cobrado por estes estados. \
    </div>');
        
}); // end



/* Funcao de comprar um produto diretamente na prateleira, pelo botao ou pelo drag and drop */
function buy(item){
    try{
    	var total,valor,totalGeral,quant;
    	var url = "/../no-cache/CarrinhoAdd.aspx";
    	var qtd = "&quantidade=1";
    	var skuId = $(item).parent().parent().parent().find(".wrapper-buy-button-asynchronous .buy-button-asynchronous-product-id").val();
    	var btDirectBuy = $(item).parent().parent().parent().find(".wrapper-buy-button-asynchronous:eq(0) span.add a.btn-add-buy-button-asynchronous");
    	var btQuickView = $(item).parent().parent().find(".quick-view a");
    	var preco = $(item).parent().parent().find("p.preco em.valor-por strong");
    	var titulo = $(item).parent().parent().find("h3>a");
    	
    	if( btDirectBuy.attr("href") !== undefined){
    		btQuickView.trigger("click");
    	}else{
    		
    	}
    }catch(e){
    }
}

function createCartProdNames(jqSelectorTarget,price,name){
		var spanTxtPrice 	= document.createTextNode(price);
		var spanTxtName 	= document.createTextNode(name);
		var spanPrice 		= document.createElement("SPAN");
		var spanName 		= document.createElement("SPAN");
		var img 			= document.createElement("IMG");
		var li 				= document.createElement("LI");
		
		//spanPrice
		spanPrice.setAttribute("class","preco");
		
		//spanName
		spanName.setAttribute("class","titulo");
		
		//img
		img.setAttribute("class","remove");
		img.setAttribute("src","img/remove.png");
		
		//appends
		spanPrice.appendChild(spanTxtPrice);
		spanName.appendChild(spanTxtName);
		
		li.appendChild(spanName);
		li.appendChild(img);
		li.appendChild(spanPrice);
		
		$(jqSelectorTarget).prepend(li);
	}

/* Funcao Recursiva que pega a quantidade de items no carrinho, e exibe */
function items_carrinho(){
	var prodNome, prodPreco,precoFinal,linhasProd;
    var url = "/../Site/Carrinho.aspx";
    var valor = $('.amount-items-in-cart .cart-info .amount-items .amount-items-em').text();
    var totalCart = $('.amount-items-in-cart .cart-info .total-cart .total-cart-em').text().replace(".","");
    
    if(valor != "0,00" && valor != ""){
    	//url json que busca pelo nome do produto:
    	///../buscaautocomplete/?maxRows=1&productNameContains=NOME_PRODUTO
        $('#carrinho .cartquantity').text(valor+" Produto(s)");
        $('#carrinho #menu .sub p span.value').text("R$ "+totalCart);
        
        //AJAX QUE PEGA O NOME DOS PRODUTOS NO CARRINHO
        $.ajax({
        	url : url,
        	dataType : "html",
        	success : function(data) {
        		//INCIO AJAX SUCCESS
        		linhasProd 	= $(data).find(".carrinhoTable tbody tr");
        		prodNome = $(data).find(".carrinhoTable tbody tr td.produto h4 a");
        		prodPreco = $(data).find(".carrinhoTable tbody tr td.preco-unitario");
        		
        		linhasProd.each(function(i){
        			//ValorUnitarioPor
        			prodPreco.eq(i).find("span").each(function(){
        				if( /ValorUnitarioPor/.test( $(this).attr("id") ) ){
        					createCartProdNames( "#carrinho-barra #carrinho #menu", "Por: "+$(this).text(), prodNome.eq(i).text().replace(/(\s+\d+)|(\s\-.*)$/,"") );
        				}
        			});
        		});
        				
        		//FIM AJAX SUCCESS
        	}
        });
    } else {
        var t = setTimeout("items_carrinho()",1000);
    }
}
